package com.feifan.Filter;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyRequestWarp extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    public MyRequestWarp(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    // 对请求request 对象的数据进行统一编码
    @Override
    public Map<String, String[]> getParameterMap() {
        // 获取请求方式
        String method = request.getMethod();
        if ("POST".equalsIgnoreCase(method)) {
            try {
                request.setCharacterEncoding("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Map<String, String[]> map = request.getParameterMap();
            return map;
        } else if ("get".equalsIgnoreCase(method)) {
            // get请求单独对请求参数单个装换
            Map<String, String[]> map = request.getParameterMap();
            System.out.println(map + ">>>>");
            if (map == null) {
                return super.getParameterMap();
            }
            Set<String> keySet = map.keySet();
            String[] value = null;
            String utf = null;
            try {
                for (String string : keySet) {
                    value = map.get(string);
                    for (int i = 0; i < value.length; i++) {
                        // 字符串转码
                        utf = new String(value[i].getBytes("iso-8859-1"), "utf-8");
                        value[i] = utf;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return super.getParameterMap();
    }

    @Override
    public String getParameter(String name) {
        // 通过value获取值
        String[] values = getParameterValues(name);
        if (values != null) {
            return values[0];
        }
        return super.getParameter(name);
    }

    @Override
    public String[] getParameterValues(String name) {
        // 通过map 集合获取值
        Map<String, String[]> parameterMap = getParameterMap();
        if (parameterMap != null) {
            return parameterMap.get(name);
        }
        return super.getParameterValues(name);
    }
}
